from fastapi.exceptions import HTTPException
from fastapiApp.models.map import Map_Node_Mo, Map_Edge_Mo
from fastapiApp.schemas.map_scheams import MapNodeCreate, MapNodeUpdate
from typing import List, Dict

class MapNodeController:
    """
    站点控制器 - 处理站点相关的数据库操作
    """
    def __init__(self):
        self.model = Map_Node_Mo

    # 检查站点是否已存在
    async def is_exist(self, obj_in: MapNodeCreate) -> int:
        """
        检查是否存在同名站点
        """
        if await self.model.filter(name=obj_in.name).exists():
            raise HTTPException(status_code=401, detail="站点名称已存在")
        return 0

    # 获取站点列表
    async def list(self, page: int = 1, page_size: int = 10) -> tuple[int, List[Dict]]:
        """
        获取站点列表，支持分页
        """
        query = await self.model.filter().offset((page - 1) * page_size).limit(page_size)
        count = await self.model.filter().count()

        data_list = [
            await data.to_dict() for data in query
        ]

        return count, data_list

    # 获取所有站点（不分页）
    async def get_all(self) -> List[Dict]:
        """
        获取所有站点信息，用于地图显示
        """
        query = await self.model.all()
        data_list = [
            await station.to_dict() for station in query
        ]

        return data_list

    # 根据ID获取站点
    async def get_by_id(self, id: int) -> Map_Node_Mo:
        """
        根据ID获取站点信息
        """
        station = await self.model.get_or_none(id=id)
        if not station:
            raise HTTPException(status_code=404, detail="站点不存在")
        return station

    # 更新站点信息
    async def update(self, obj_in: MapNodeUpdate) -> None:
        """
        更新站点信息
        """
        station = await self.get_by_id(obj_in.id)

        # 检查是否更改了名称且新名称已存在
        if obj_in.name != station.name and await self.model.filter(name=obj_in.name, id__not=obj_in.id).exists():
            raise HTTPException(status_code=401, detail="站点名称已存在")

        station.name = obj_in.name
        station.type = obj_in.type
        station.status = obj_in.status
        station.x = obj_in.x
        station.y = obj_in.y
        station.description = obj_in.description

        await station.save()

    # 删除站点
    async def delete(self, id: int) -> None:
        """
        删除站点
        """
        station = await self.get_by_id(id)
        await station.delete()

# 创建控制器实例
map_node_controller = MapNodeController()

class MapEdgeController:
    """
    地图边控制器 - 处理地图边相关的数据库操作
    """
    def __init__(self):
        self.model = Map_Edge_Mo


map_edge_controller = MapEdgeController()